package com.moarea.app.service.abst;

import com.moarea.app.exception.GlobalCustomException;
import com.moarea.app.service.inter.IFileService;

import java.io.*;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

/**
 * 文件处理接口实现类
 * <p>
 * jizhong
 * <p>
 * 2017-09-20
 */
public abstract class AFileService extends AFTPService implements IFileService {

    private static final int BUFFER_SIZE = 2 * 1024;

    /**
     * 将文件从就地址保存到新地址
     *
     * @param fileName 文件名
     * @param oldPath  旧地址
     * @param newPath  新地址
     */
    @Override
    public boolean readFileToNewPath(String fileName, String oldPath, String newPath) {

        File dictionary = new File(newPath);
        if (!dictionary.exists()) {
            dictionary.mkdirs();
        }

        File oldFile = new File(oldPath.concat("/").concat(fileName));
        if (!oldFile.exists()) return false;

        // 构建流对象
        FileInputStream fileInputStream;
        BufferedInputStream bufferedInputStream;
        FileOutputStream fileOutputStream;
        BufferedOutputStream bufferedOutputStream;
        try {

            fileInputStream = new FileInputStream(oldFile);
            bufferedInputStream = new BufferedInputStream(fileInputStream);
            fileOutputStream = new FileOutputStream(new File(newPath.concat("/").concat(fileName)));
            bufferedOutputStream = new BufferedOutputStream(fileOutputStream);

            byte[] bytes = new byte[2048];// 字节数组，存储读取的数据

            int len;
            while ((len = bufferedInputStream.read(bytes)) != -1) {
                bufferedOutputStream.write(bytes, 0, len);
                bufferedOutputStream.flush();
            }

            fileInputStream.close();
            bufferedInputStream.close();
            fileOutputStream.close();
            bufferedOutputStream.close();

            return true;

        } catch (IOException e) {
            e.printStackTrace();
        }

        return false;
    }

    /**
     * 根据文件路径删除文件
     *
     * @param filePath 文件路径（路径+文件名）
     * @return 删除是否成功
     */
    @Override
    public boolean deleteFileFromDisk(String filePath) {

        File file = new File(filePath);
        return file.exists() && file.delete();

    }

    /**
     * 生成ZIP文件
     *
     * @param files   待压缩的文件
     * @param zipFile 压缩文件
     */
    public void zipFiles(List<File> files, File zipFile) {

        byte bytes[] = new byte[1024];
        try {
            ZipOutputStream zipOutputStream = new ZipOutputStream(new FileOutputStream(zipFile));

            for (File file : files) {

                FileInputStream fileInputStream = new FileInputStream(file);
                zipOutputStream.putNextEntry(new ZipEntry(file.getName()));

                int len;
                while ((len = fileInputStream.read(bytes)) > 0) {
                    zipOutputStream.write(bytes, 0, len);
                }
                zipOutputStream.closeEntry();
                fileInputStream.close();
            }

            zipOutputStream.close();

        } catch (IOException e) {
            throw new GlobalCustomException(e.getMessage());
        }
    }


    /**
     * 压缩成ZIP 方法1
     *
     * @param srcDir           压缩文件夹路径
     * @param zipFile          压缩文件保存的完整路径
     * @param KeepDirStructure 是否保留原来的目录结构,true:保留目录结构;
     *                         false:所有文件跑到压缩包根目录下(注意：不保留目录结构可能会出现同名文件,会压缩失败)
     * @throws RuntimeException 压缩失败会抛出运行时异常
     */
    public void zip(String srcDir, String zipFile, boolean KeepDirStructure)
            throws RuntimeException {

        ZipOutputStream zos = null;
        try {
            FileOutputStream out = new FileOutputStream(zipFile);
            zos = new ZipOutputStream(out);
            File sourceFile = new File(srcDir);
            compress(sourceFile, zos, sourceFile.getName(), KeepDirStructure);
        } catch (Exception e) {
            throw new RuntimeException("zip error from ZipUtils", e);
        } finally {
            if (zos != null) {
                try {
                    zos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

    }

    /**
     * 压缩成ZIP 方法2
     *
     * @param srcFiles 需要压缩的文件列表
     * @param zipFile  压缩文件保存路径
     * @throws RuntimeException 压缩失败会抛出运行时异常
     */
    public void zip(List<File> srcFiles, String zipFile) throws RuntimeException {
        ZipOutputStream zos = null;

        try {
            FileOutputStream out = new FileOutputStream(zipFile);
            zos = new ZipOutputStream(out);
            for (File srcFile : srcFiles) {
                byte[] buf = new byte[BUFFER_SIZE];
                zos.putNextEntry(new ZipEntry(srcFile.getName()));
                int len;
                FileInputStream in = new FileInputStream(srcFile);
                while ((len = in.read(buf)) != -1) {
                    zos.write(buf, 0, len);
                }
                zos.closeEntry();
                in.close();
            }
        } catch (Exception e) {
            throw new RuntimeException("zip error from ZipUtils", e);
        } finally {

            if (zos != null) {
                try {
                    zos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }


    /**
     * 递归压缩方法
     *
     * @param sourceFile       源文件
     * @param zos              zip输出流
     * @param name             压缩后的名称
     * @param KeepDirStructure 是否保留原来的目录结构,true:保留目录结构;
     *                         false:所有文件跑到压缩包根目录下(注意：不保留目录结构可能会出现同名文件,会压缩失败)
     * @throws Exception
     */
    private void compress(File sourceFile, ZipOutputStream zos, String name,
                          boolean KeepDirStructure) throws Exception {
        byte[] buf = new byte[BUFFER_SIZE];
        if (sourceFile.isFile()) {
            // 向zip输出流中添加一个zip实体，构造器中name为zip实体的文件的名字
            zos.putNextEntry(new ZipEntry(name));
            // copy文件到zip输出流中
            int len;
            FileInputStream in = new FileInputStream(sourceFile);
            while ((len = in.read(buf)) != -1) {
                zos.write(buf, 0, len);
            }
            // Complete the entry
            zos.closeEntry();
            in.close();
        } else {
            File[] listFiles = sourceFile.listFiles();
            if (listFiles == null || listFiles.length == 0) {
                // 需要保留原来的文件结构时,需要对空文件夹进行处理
                if (KeepDirStructure) {
                    // 空文件夹的处理
                    zos.putNextEntry(new ZipEntry(name + "/"));
                    // 没有文件，不需要文件的copy
                    zos.closeEntry();
                }

            } else {
                for (File file : listFiles) {
                    // 判断是否需要保留原来的文件结构
                    if (KeepDirStructure) {
                        // 注意：file.getName()前面需要带上父文件夹的名字加一斜杠,
                        // 不然最后压缩包中就不能保留原来的文件结构,即：所有文件都跑到压缩包根目录下了
                        compress(file, zos, name + "/" + file.getName(), KeepDirStructure);
                    } else {
                        compress(file, zos, file.getName(), KeepDirStructure);
                    }

                }
            }
        }
    }

    /**
     * 将文件读成字符串
     * <p>
     * jizhong
     * <p>
     * 2017-10-10
     *
     * @param filePath 文件路径
     * @return 字符串
     */
    @Override
    public String readXmlToString(String filePath) {
        //读取文件
        BufferedReader br = null;
        StringBuffer sb = null;
        try {
            br = new BufferedReader(new InputStreamReader(new FileInputStream(filePath), "UTF-8")); //这里可以控制编码
            sb = new StringBuffer();
            String line;
            while ((line = br.readLine()) != null) {
                sb.append(line);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                br.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        return new String(sb);
    }
}
